#include "jobs.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_JOBS 512

struct Job {
    pid_t pid;
    size_t job_num;
    char * command;
};

struct Job jobs[MAX_JOBS];
size_t job_count = 0;
//size_t current_job = MAX_JOBS;

size_t add_job( pid_t pid, const char * command )
{
    if ( job_count >= MAX_JOBS )
        return MAX_JOBS;

    jobs[job_count].pid = pid;
    jobs[job_count].job_num = ( job_count == 0 ) ? 1 : jobs[job_count - 1].job_num + 1;
    jobs[job_count].command = malloc( 1 + strlen(command) * sizeof(char) );
    strcpy( jobs[job_count].command, command );

//    current_job = jobs[job_count].job_num;

    printf( "[%lu] %d\n", jobs[job_count].job_num, pid );

    return jobs[job_count++].job_num;
}

void print_jobs()
{
    for ( int i = 0; i < job_count; i++ )
    {
        printf( "[%lu]", jobs[i].job_num );
/*
        if ( current_job == jobs[i].job_num )
            printf("+");
        else
            printf( "-" );
*/
        printf( "\t\t\t%s\n", jobs[i].command );
    }
}

size_t number_of_jobs()
{
    return job_count;
}

void remove_job( size_t jobnum )
{
    size_t location = MAX_JOBS;

    //Find job
    for ( size_t i = 0; i < job_count; i++ )
    {
        if ( jobs[i].job_num == jobnum ) {
            location = i;
            break;
        }
    }

    //Job does not exist
    if ( location == MAX_JOBS )
        return;

    struct Job temp = jobs[location];

    for ( size_t i = location + 1; i < job_count; i++ )
    {
        jobs[i - 1] = jobs[i];
    }

    job_count--;

    printf("[%lu] Done\t\t\t%s\n", temp.job_num, temp.command );
    free( temp.command );
}

size_t remove_queue[MAX_JOBS];
size_t remove_queue_size = 0;

void delay_remove_job_pid( pid_t pid )
{
    size_t jobnum = 0;

    for ( size_t i = 0; i < job_count; i++ )
    {
        if ( jobs[i].pid == pid ) {
            jobnum = jobs[i].job_num;
            break;
        }
    }

    if ( jobnum == 0 )
        return;

    if ( remove_queue_size >= MAX_JOBS )
        return;

    //Should probably search through this list first to ensure no duplicate entries
    remove_queue[remove_queue_size++] = jobnum;
}

void do_remove_jobs()
{
    for ( size_t i = 0; i < remove_queue_size; i++ )
    {
        remove_job( remove_queue[i] );
    }
}
